package com.cqeec.util;

import com.google.common.base.Supplier;

import java.sql.*;
import java.util.*;

/**
 * 孤独的灯塔<br/>
 * date:2020/1/7<br/>
 *
 * @Author:hxh 1361973421@qq.com
 */
public class MyUtil {

    private static  String DRIVER = "com.mysql.jdbc.Driver";
    private static  String URL = "jdbc:mysql://47.105.152.138:3907/test_compass?useSSL=false";
    private static  String USERNAME = "deao";
    private static  String PASSWORD = "Y!5LIL*xG@%DWAaf^!8l";

    private static final String SQL = "SELECT * FROM ";// 数据库操作

    /**
     * 获取数据库连接
     *
     * @return
     */
    public static Connection getConnection()  throws Exception {
        Connection conn = null;
        conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        return conn;
    }

    /**
     * 获取表中所有字段名称集合
     * @return
     */
    public static List<Field> getFieldsByTableName(String tableName) throws Exception  {
        List<Field> fields = new ArrayList();
        //与数据库的连接
        Connection conn = getConnection();
        PreparedStatement pStemt = null;
        String tableSql = SQL + tableName;
        pStemt = conn.prepareStatement(tableSql);
        //结果集元数据
        ResultSetMetaData rsmd = pStemt.getMetaData();
        ResultSet  rs = pStemt.executeQuery("show full columns from " + tableName);
        //表列数
        int size = rsmd.getColumnCount();
        for (int i = 0; i < size; i++) {
            rs.next();
            Field field =new Field();
            field.setJavaType(covertJdbcType(rsmd.getColumnTypeName(i + 1)));
            field.setJavaName(covertFieldName(rsmd.getColumnName(i + 1)));
            field.setDatabaseName(rsmd.getColumnName(i + 1));
            field.setComment(rs.getString("Comment"));
            fields.add(field);
        }
        return fields;
    }

    /**
     * 模糊查询表名
     * @param name
     * @return
     * @throws Exception
     */
    public static List<String> getTablesByName(String name) throws Exception{
        List<String> list=new ArrayList<>();
        if(name!=null&&!"".equals(name.trim())){
            name="%"+name+"%";
        }else{
            name=null;
        }
        DatabaseMetaData meta = getConnection().getMetaData();
        ResultSet rs = meta.getTables(null, null, name,
                new String[] { "TABLE" });
        while (rs.next()) {
            list.add(rs.getString(3));
        }
        return list;
    }

    /**
     * 生成xml文件
     * @param data
     * @return
     */
    public static String generateXml(GenerateXmlData data) {
        Supplier supplier = ()->"templates/page.xml.vm";
        return VelocityEngineBuilder.startWithDefault()
                .withTemplatePath(supplier)
                .withContextBuild()
                .setKV("data", data)
                .getString();
    }

    /**
     * 生成xml文件
     * @param data
     * @return
     */
    public static String generateInfo(GenerateXmlData data) {
        Supplier supplier = ()->"templates/info.xml.vm";
        return VelocityEngineBuilder.startWithDefault()
                .withTemplatePath(supplier)
                .withContextBuild()
                .setKV("data", data)
                .getString();
    }









    private static String covertJdbcType(String feildType){
        if("varchar".equalsIgnoreCase(feildType)||"char".equalsIgnoreCase(feildType)||"text".equalsIgnoreCase(feildType)){
            return "VARCHAR";
        }
        if("int".equalsIgnoreCase(feildType)||"smallint".equalsIgnoreCase(feildType)||"integer".equalsIgnoreCase(feildType)){
            return "INTEGER";
        }
        if("decimal".equalsIgnoreCase(feildType)) {
            return "DECIMAL";
        }
        if("bigint".equalsIgnoreCase(feildType)){
            return "LONG";
        }
        if("double".equalsIgnoreCase(feildType)||"float".equalsIgnoreCase(feildType)){
            return "DOUBLE";
        }
        if("datetime".equalsIgnoreCase(feildType)||"date".equalsIgnoreCase(feildType)||"time".equalsIgnoreCase(feildType)||"timestamp".equalsIgnoreCase(feildType)){
            return "TIMESTAMP";
        }
        throw new RuntimeException("表字段类型找不到匹配的jdbcType");
    }

    private static String covertFieldName(String fieldName){
        if(fieldName.indexOf("_")!=-1) {
            String[] temps=fieldName.split("_");
            StringBuffer sb=new StringBuffer();
            for(String temp:temps) {
                sb.append(firstLetterUpper(temp));
            }
            fieldName=sb.toString();
        }else {
            fieldName=firstLetterLower(fieldName);
        }
        fieldName=firstLetterLower(fieldName);
        return fieldName;
    }
    public static String covertTableName(String fieldName){
        if(fieldName.indexOf("_")!=-1) {
            String[] temps=fieldName.split("_");
            StringBuffer sb=new StringBuffer();
            for(String temp:temps) {
                sb.append(firstLetterUpper(temp));
            }
            fieldName=sb.toString();
        }else {
            fieldName=firstLetterLower(fieldName);
        }
        return fieldName;
    }


    public static String firstLetterUpper(String str) {
        return str.substring(0, 1).toUpperCase()+str.substring(1);
    }
    public static String firstLetterLower(String str) {
        return str.substring(0, 1).toLowerCase()+str.substring(1);
    }

}
